/*
 * Copyright (c) 2017. 杭州端点网络科技有限公司.  All rights reserved.
 */

package com.jiantong.admin.controller;

import com.google.common.base.CharMatcher;
import com.jiantong.common.model.BaseLoginUser;
import com.jiantong.user.enums.LoginType;
import com.jiantong.user.model.User;
import com.jiantong.user.service.UserReadService;
import com.jiantong.web.core.util.LoginUserMaker;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.exception.JsonResponseException;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : panxin
 */
@Slf4j
@RestController
@RequestMapping
public class AdminUsers {

    @RpcConsumer
    private UserReadService<User> userReadService;

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户信息
     */
    @RequestMapping(value = "/api/admin/user/login", method = RequestMethod.GET, produces = "application/json")
    public BaseLoginUser login(@RequestParam String username,
                               @RequestParam String password,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        LoginType type;
        if (CharMatcher.DIGIT.matchesAllOf(username)) {
            type = LoginType.MOBILE;
        } else if (CharMatcher.is('@').matchesAnyOf(username)) {
            type = LoginType.EMAIL;
        } else {
            type = LoginType.NAME;
        }

        Response<User> userResp = userReadService.login(username, password, type);
        if (!userResp.isSuccess()) {
            log.warn("try login user failed, username = {}, error = {}", username, userResp.getError());
            throw new JsonResponseException(userResp.getError());
        }
        User user = userResp.getResult();
        return LoginUserMaker.from(user);
    }

}
